package ar.com.coonocer.joy.mdg.util.loader;

import java.util.MissingResourceException;
import java.util.ResourceBundle;

import org.w3c.dom.Node;

public class UMLObjectFactory {

	private static final String NAMESPACE_UML = "UML";

	//private static Log logger = LogFactory.getLog(UMLObjectFactory.class);

	private static ResourceBundle propsDefault = ResourceBundle.getBundle("ar.com.coonocer.joy.mdg.util.loader.UMLObjectFactory");

	private static ResourceBundle propsExt = ResourceBundle.getBundle("ar.com.coonocer.joy.mdg.util.loader.UMLObjectFactoryExtensions");

	public static Object instantiateObjectForNode(Node node) {
		//
		String nodeName = node.getNodeName();
		//
		//logger.debug("Instantiating class for " + node.getNodeName());
		//
		if (!nodeName.startsWith(NAMESPACE_UML + ":")) {
			throw new RuntimeException("Unable to instantiate class for " + nodeName + ". Node name should start with " + NAMESPACE_UML + ":");
		}
		//
		String key = "UML_" + nodeName.substring(nodeName.indexOf(':') + 1);
		//
		String className = null;
		try {
			className = propsExt.getString(key);
		} catch (MissingResourceException e) {
		}
		if (className == null) {
			try {
				className = propsDefault.getString(key);
			} catch (MissingResourceException e) {
			}
		}
		if (className == null) {
			throw new RuntimeException("Unable to instantiate class for " + nodeName + ". Key not found in UMLObjectFactory.properties. Key:" + key);
		}
		//
		try {
			return Class.forName(className).newInstance();
		} catch (InstantiationException e) {
			throw new RuntimeException("Unable to instantiate class for " + nodeName, e);
		} catch (IllegalAccessException e) {
			throw new RuntimeException("Unable to instantiate class for " + nodeName, e);
		} catch (ClassNotFoundException e) {
			throw new RuntimeException("Unable to instantiate class for " + nodeName, e);
		} catch (ClassCastException e) {
			throw new RuntimeException("Unable to instantiate class for " + nodeName, e);
		}
	}

}